<template>
	<view class="page">
		<u--form labelPosition="left" labelWidth="200rpx" ref="uForm" :model="form" :rules="formRules">
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">患者信息</view>
			<view class="card-container">
				<u-form-item label="姓名" prop="memberName" borderBottom required>
					<u--input v-model="form.memberName"  border="none" placeholder="请填写姓名" :disabled='form.tranStatus!==1'></u--input>
					<u-icon slot="right" name="account-fill" size="20px" @click="onSelectDiseasePopup"></u-icon>
				</u-form-item>
				<u-form-item label="身份证号" prop="idcard" borderBottom>
					<u--input v-model="form.idcard" border="none" type="number" placeholder="请填写身份证号" :disabled='form.tranStatus!==1'
						@change='calAge'></u--input>
				</u-form-item>
				<u-form-item label="出生日期" prop="birth" borderBottom>
					<uni-datetime-picker type="date" :clear-icon="false" :border='false' v-model="form.birth" :disabled='form.tranStatus!==1'
						@change='birthConfirm' />
					<!-- <view class="input-text" :class="{'placeholder-color': !form.birth}">
						{{form.birth?form.birth:'请选择日期'}}</view> -->
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="性别" prop="gender" borderBottom>
					<u-radio-group v-model="form.gender" placement="row" :disabled='form.tranStatus!==1'>
						<u-radio :customStyle="{marginRight: '16px'}" label="男" :name="1"></u-radio>
						<u-radio :customStyle="{marginRight: '8px'}" label="女" :name="2"></u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item label="年龄" prop="age" borderBottom required>
					<u--input v-model="form.age" border="none" type="number" placeholder="请填写年龄" :disabled='form.tranStatus!==1'></u--input>
				</u-form-item>
				<u-form-item label="患者联系电话" prop="phoneNumber">
					<u--input v-model="form.phoneNumber" border="none" type='number' placeholder="请填写手机号" :disabled='form.tranStatus!==1'></u--input>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">病例信息</view>
			<view class="card-container">
				<u-form-item label="患者主诉" prop="mainsuit" borderBottom required>
					<u--textarea v-model="form.mainsuit" placeholder="请输入患者主诉" :disabled='form.tranStatus!==1'></u--textarea>
				</u-form-item>
				<u-form-item label="初步诊断" prop="assessmentcontent" borderBottom required>
					<u--textarea v-model="form.assessmentcontent" placeholder="请输入临床诊断" :disabled='form.tranStatus!==1'></u--textarea>
				</u-form-item>
				<u-form-item label="备注" prop="notes" borderBottom>
					<u--textarea v-model="form.notes" placeholder="请输入备注" :disabled='form.tranStatus!==1'></u--textarea>
				</u-form-item>
			</view>
			<u-gap height="32rpx" bgColor="transparent"></u-gap>
			<view class="form-card-title">转诊申请信息</view>
			<view class="card-container">
				<u-form-item label="申请转入医院" prop="tranHospitalId" borderBottom @click="tranHospitalIdShow=true"
					required>
					<view class="input-text" :class="{'placeholder-color': !form.tranHospitalId}">
						{{form.tranHospitalName?form.tranHospitalName:'请选择接诊医院'}}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="申请转入科室" prop="tranDeptId" borderBottom @click="tranDeptIdShow=true" required>
					<view class="input-text" :class="{'placeholder-color': !form.tranDeptId}">
						{{form.tranDeptName?form.tranDeptName:'请选择接诊科室'}}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="预计到诊时间" prop="tranTime" @click="tranTimeShow = true" required>
					<view class="input-text" :class="{'placeholder-color': !form.tranTime}">
						{{form.tranTime?form.tranTime.split(' ')[0]:'请选择日期'}}
					</view>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
			</view>
			<view v-if="form.tranStatus===9||form.tranStatus===8">
				<u-gap height="32rpx" bgColor="transparent"></u-gap>
				<view class="form-card-title">转诊接诊信息</view>
				<view class="card-container">
					<u-cell-group :border="false">
						<u-cell title="接诊医院" :value="form.tranHospitalName"></u-cell>
						<u-cell title="接诊科室" :value="form.tranDeptName"></u-cell>
						<u-cell title="接诊医生" :value="form.receiveDoctor"></u-cell>
						<u-cell title="接诊日期" :value="form.receiveDate"></u-cell>
					</u-cell-group>
				</view>
			</view>
			<view v-if="form.tranStatus===4">
				<u-gap height="32rpx" bgColor="transparent"></u-gap>
				<view class="form-card-title">驳回信息</view>
				<view class="card-container">
					<u-cell-group :border="false">
						<u-cell title="操作人" :value="form.refuseUserName"></u-cell>
						<u-cell title="驳回信息" :value="form.refuseReason"></u-cell>
					</u-cell-group>
				</view>
			</view>
	</u--form>
	<view class="button-group-list" v-if="form.tranStatus===1">
		<u-button class="save-entry-button" type="warning" text="暂存" shape="circle" @click="onSubmit('1')"></u-button>
		<u-button class="save-button" type="primary" text="保存" shape="circle" @click="onSubmit('5')"></u-button>
	</view>
	<u-popup mode="bottom" :show="tranDiseaseNameShow" :closeable='true' @close="tranDiseaseNameShow=false"
		@open="tranDiseaseNameShow=true">
		<view class="popupsty">
			<u--form labelPosition="left" labelWidth="140rpx">
				<u-form-item label="疾病名称" prop="namea" borderBottom>
					<u--input v-model="filterForm.namea" border="none" placeholder="请填写名称"></u--input>
				</u-form-item>
				<u-form-item label="疾病编码" prop="namec" borderBottom>
					<u--input v-model="filterForm.namec" border="none" placeholder="请填写编码"></u--input>
				</u-form-item>
				<u-form-item label="拼音码" prop="nameb" borderBottom>
					<u--input v-model="filterForm.nameb" border="none" placeholder="请填写拼音码"></u--input>
				</u-form-item>
			</u--form>
			<div style="display: flex;">
				<u-button class="butStyle" type="primary" text="查询" size='mini' @click="selectICD"></u-button>
				<u-button class="butStyle" type="primary" text="确定" size='mini' @click="onConfirm"></u-button>
			</div>

			<view class="uni-container">
				<uni-table ref="table" :loading="loading" border stripe type="selection" emptyText="暂无更多数据"
					@selection-change="selectionChange" style="height: 800rpx;">
					<uni-tr>
						<uni-th width="100" align="center">疾病名称</uni-th>
						<uni-th width="100" align="center">疾病编码</uni-th>
						<!-- <uni-th width="100" align="center">拼音码</uni-th> -->
					</uni-tr>
					<uni-tr v-for="(item, index) in tableData" :key="index">
						<uni-td>{{ item.diseaseName }}</uni-td>
						<uni-td>
							<view class="name">{{ item.icdCode}}</view>
						</uni-td>
						<!-- <uni-td align="center">{{ item.pinyinCode }}</uni-td> -->
					</uni-tr>
				</uni-table>

			</view>
			<view class="uni-pagination-box"><uni-pagination show-icon :total="pageInfo.total" @change="pagChange" />
			</view>
		</view>
	</u-popup>

	<!--出生日期选择-->
	<u-datetime-picker :show="birthShow" v-model="birth" mode="date" @confirm='birthConfirm' @cancel='birthShow=false'
		:closeOnClickOverlay='true' :minDate="0"></u-datetime-picker>

	<!--证件类型选择-->
	<u-picker :show="certTypeShow" :columns="cardTypeDict" :closeOnClickOverlay='true' keyName="name"
		@confirm='certTypeConfirm' @cancel='certTypeShow=false' @close="certTypeShow = false"></u-picker>

	<!--接诊医院选择-->
	<u-picker :show="tranHospitalIdShow" :columns="hospitalSuperiorsList" :closeOnClickOverlay='true' keyName="name"
		@confirm='tranHospitalIdConfirm' @cancel='tranHospitalIdShow=false'
		@close="tranHospitalIdShow = false"></u-picker>

	<!--接诊科室选择-->
	<u-picker :show="tranDeptIdShow" :columns="deptIdList" :closeOnClickOverlay='true' keyName="name"
		@confirm='tranDeptIdConfirm' @cancel='tranDeptIdShow=false' @close="tranDeptIdShow = false"></u-picker>

	<!--到诊时间选择-->
	<u-calendar :show="tranTimeShow" @confirm="tranTimeConfirm" @close='tranTimeShow=false' showLunar
		closeOnClickOverlay></u-calendar>

	<!--出生时间选择-->
	<u-calendar :show="birthTimeShow" @confirm="birthTimeConfirm" @close='birthTimeShow=false' showLunar
		closeOnClickOverlay></u-calendar>
	<!--选择患者组件-->
	<select-disease-popup-com ref="selectDiseasePopup" @select="onSelectDisease"></select-disease-popup-com>
	</view>
</template>

<script>
	import {
		validateIdCard,
		formatDateTime,
		formatTimestamp,
		formatDate,
		getInfoFromIdCard,
		calculateAge
	} from '../../../util/utils';
	import {
		ndictionary,
		addill,
		v1HospitalSuperiors,
		v1DepartmentsList,
		v1TowwaySaveUpdateApi
	} from '../../../common/api/referral/add/add';

	import selectDiseasePopupCom from '@/components/select-disease-popup-com/select-disease-popup-com.vue'
	import {
		readApply
	} from '@/common/api/referral/detail/detail.js'
	export default {
		components: {
			selectDiseasePopupCom
		},
		onLoad(option) {
			this.getDetail(option.id)
			this.getIdcardType()
			this.getHospitalSuperiors()
		},
		data() {
			return {
				birthTimeShow: false,
				pageSize: 10,
				pageCurrent: 1,
				total: '',
				loading: false,
				tranTimevalue: Number(new Date()),
				tranTimeShow: false,
				birthShow: false,
				birth: Number(new Date()),
				certTypeShow: false,
				certType: '居民身份证',
				tranHospitalIdShow: false,
				tranHospitalId: '',
				tranDiseaseNameShow: false,
				tranDeptIdShow: false,
				tranDeptId: '',
				form: {
					notes: "",
					memberName: "",
					certType: "cert_1",
					insuranceType: "",
					age: "",
					nation: "",
					height: "",
					gender: null,
					idcard: "",
					insuranceNumber: "",
					phoneNumber: "",
					folk: "",
					weight: "",
					birth: '',
					professionType: "",
					workUnit: "",
					homeAddress: "",
					provinceCode: "",
					cityCode: "",
					districtCode: "",
					tranDisease: "",
					icdDisease: "",
					mainsuit: "",
					assessmentcontent: "",
					tranGoal: "",
					patientHistory: "",
					nowHistory: "",
					pastHistory: "",
					allergyHistory: "",
					familyHistory: "",
					hospitalDrug: "",
					treatmentHistory: "",
					healthCheck: "",
					supplementaryInstruction: "",
					caseImages: "",
					tranHospitalId: "",
					tranHospitalName: "",
					tranDeptId: "",
					tranDeptName: "",
					tranTime: "",
					applyHospitalName: uni.getStorageSync('hospitalName'),
					applyHospitalId: uni.getStorageSync('hospitalId'),
					applyDeptId: uni.getStorageSync('deptId'),
					applyDeptName: uni.getStorageSync('deptName'),
					applyDoctorId: uni.getStorageSync('doctorId'),
					applyDoctorName: uni.getStorageSync('doctorName'),
					receiveType: 0,
					applyDoctorPhone: uni.getStorageSync('doctorPhone'),
					tranType: "0",
					flag: "",
					id: ""
				},
				filterForm: {
					namea: "", // 疾病名称
					nameb: "", // 疾病拼音码
					namec: "" // 疾病编码
				},
				pageInfo: {
					total: 0,
					offset: 0,
					limit: 10,
				},
				formRules: {
					'memberName': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					'age': {
						type: 'number',
						required: true,
						message: '请填写年龄',
						trigger: ['blur', 'change'],
					},

					'mainsuit': {
						type: 'string',
						required: true,
						message: '请填写主诉',
						trigger: ['blur', 'change']
					},
					'assessmentcontent': {
						type: 'string',
						required: true,
						message: '请填写诊断',
						trigger: ['blur', 'change']
					},

					'tranHospitalId': {
						type: 'string',
						required: true,
						message: '请选择医院',
						trigger: ['blur', 'change']
					},
					'tranDeptId': {
						type: 'string',
						required: true,
						message: '请选择科室',
						trigger: ['blur', 'change']
					},
					'tranTime': [
						// 必填验证
						{
							type: 'string',
							required: true,
							message: '请填写时间',
							trigger: ['blur', 'change'],
						},
						// 额外添加长度验证规则
						// {
						// 	validator: (rule, value, callback) => {
						// 		const regex = /^\d{4}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])$/;
						// 		if (value.length !== 8||!regex.test(value)) {
						// 			callback(new Error('请输入格式为 20250101 的8位纯数字日期'));
						// 		} else {
						// 			callback();
						// 		}
						// 	},
						// 	trigger: 'blur'
						// }
					],
					'phoneNumber': {
						type: 'number',
						message: '请填写数字',
						trigger: ['blur', 'change']
					},
					idcard: [{
						validator: (rule, value, callback) => {
							if (value && !validateIdCard(value)) {
								return false;
							}
							return true;
						},
						message: '请输入正确的身份证号码',
						trigger: ['blur', 'change']
					}],
				},
				cardTypeDict: [],
				tableData: [],
				hospitalSuperiorsList: [],
				deptIdList: []
			}
		},
		watch: {
			"form.tranHospitalId": {
				handler(val) {
					v1DepartmentsList(val).then(res => {
						if (res.code === 1) {
							let dict = []
							for (let i = 0; i < res.object.length; i++) {
								let item = res.object[i]
								dict.push({
									name: item.deptNickname,
									value: item.id
								})
							}
							this.deptIdList = [dict]
						}
					})
				}
			},
		},
		methods: {
			getDetail(id) {
				const data = {
					id: id,
					modeId: "upapply",
				};
				readApply(data).then((res) => {

					this.form = res.object.transfer;
				})
			},
			// 通过身份证计算年龄和性别
			calAge(value) {
				this.$refs.uForm.validateField('idcard', (res) => {
					if (!res[0]?.message) {
						if (!value) {
							this.form.age = '';
							this.form.gender = null,
								this.form.birth = ''
							return;
						}
						const idCardInfo = getInfoFromIdCard(value);
						if (idCardInfo) {
							this.form.age = idCardInfo.age;
							this.form.gender = idCardInfo.gender
							this.form.birth = idCardInfo.idCardAge
						}
					}
				})
			},
			/**
			 * 打开选择患者弹框
			 */
			onSelectDiseasePopup() {
				this.$refs.selectDiseasePopup.open()
			},
			/**
			 * 选择患者
			 */
			onSelectDisease(e) {
				if (e) {
					this.form.memberName = e[0].name
					this.form.idcard = e[0].idNo
				}
			},
			// 获取医院列表
			getHospitalSuperiors() {
				v1HospitalSuperiors().then((response) => {
					if (response.code == 1) {
						let dict = []
						for (let i = 0; i < response.object.length; i++) {
							let item = response.object[i]

							dict.push({
								name: item.orgName,
								value: item.id
							})
						}
						this.hospitalSuperiorsList = [dict]
					}
				});
			},
			selectionChange(e) {
				const selectedIndexs = e.detail.index
				this.selectedElements = selectedIndexs.map(index => this.tableData[index]);
			},
			// 获取身份证类型
			getIdcardType() {
				ndictionary("KBA_CERT_TYPE").then(res => {
					if (res.code == 1) {
						let dicts = []
						for (let key in res.result.list) {
							dicts.push({
								name: res.result.list[key],
								value: key
							})
						}
						this.cardTypeDict = [dicts]
					}
				})
			},
			// 身份类型确认按钮
			certTypeConfirm(e) {
				const {
					value,
					name
				} = e.value[0]
				this.form.certType = value
				this.certType = name
				this.certTypeShow = false
			},
			// 年月日确定按钮
			birthConfirm(e) {
				this.form.age = calculateAge(e);
			},
			// 接诊医院确认按钮
			tranHospitalIdConfirm(e) {
				const {
					value,
					name
				} = e.value[0]
				this.form.tranHospitalId = value
				this.form.tranHospitalName = name
				this.tranHospitalIdShow = false
			},
			// 科室确定按钮
			tranDeptIdConfirm(e) {
				const {
					value,
					name
				} = e.value[0]
				this.form.tranDeptId = value
				this.form.tranDeptName = name
				this.tranDeptIdShow = false
			},
			// 接诊时间确认
			tranTimeConfirm(e) {
				this.form.tranTime = e[0]
				this.tranTimeShow = false
			},
			// 出生时间确认
			birthTimeConfirm(e) {
				this.form.birth = e[0]
				this.birthTimeShow = false
			},
			onSubmit(e) {
				this.$refs.uForm.validate().then(valid => {
					if (valid) {
						this.form.tranTime = this.form.tranTime.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')
						// this.form.tranHospitalName = this.tranHospitalId
						// this.form.tranDeptName = this.tranDeptId
						this.form.flag = e
						v1TowwaySaveUpdateApi(this.form).then(res => {
							if (res.code === 1) {
								uni.showToast({
									title: '提交成功',
									icon: 'success'
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									})
								}, 1000);
							}
						})
					}
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.uni-pagination-box {
		margin-top: 10rpx;
	}

	.butStyle {
		width: 100rpx;
		height: 50rpx;
		margin-top: 10rpx;
		margin-bottom: 10rpx;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}

	.popupsty {
		width: 100%;
		height: 100%;
		margin: 60rpx 10rpx 0;
	}

	.page {
		padding: 0 0 calc(64rpx + 120rpx + env(safe-area-inset-bottom)) 0;
		box-sizing: border-box;
	}

	.form-card-title {
		padding: 0 42rpx 16rpx;
		font-size: $ft-size-md;
		color: $text-desc-color;
	}

	.card-container {
		padding: 0 20rpx;
	}

	.button-group-list {
		position: fixed;
		left: 32rpx;
		bottom: calc(32rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		width: 686rpx;
		height: 120rpx;
		border-radius: 1000rpx;
		z-index: 10;

		.save-button {
			margin: 0 20rpx;
			width: 320rpx
		}

		.save-entry-button {
			margin-left: 10rpx;
			width: 320rpx;
		}
	}
</style>